import cgi
import os
from google.appengine.ext.webapp import template

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp.util import login_required

import models
import data
import urlparse
from models import Chapter
from models import Book
from models import Person
from models import Note

#Finding Person's from users:

#Find current person, if exists (else None)
def findCurrentPerson():
    return findPerson(users.get_current_user())

def findPerson(auser):
    if not auser: return None
    person = Person().all().filter("user =", auser)
    if person.count() > 0:
        return person[0]
    else:
        return None

#Find the current users - if doesn't exist, creates them! Get's them one way or another though!!!
def getCurrentPerson():
    person = findCurrentPerson()
    
    #If not find, make with our standard initialisation...
    if person == None:
        person = Person()
        person.user = users.get_current_user()
        person.lasttrans = "WEB"  #By default have them use WEB
        person.lastread = 45   #Romans
        person.opusno = 0   #Romans
        person.automarks = initialAutomarks()  #1 for all, except Romans - which will be Romans 8!
    return person;

#List of 66 1's; and then the 45'th element is 8!
def initialAutomarks():
    l = []
    for i in range(66):
        l.append(1)
    l[44] = 8
    return l


class Intro(webapp.RequestHandler):
    def get(self):

        template_values = {
            }

        path = os.path.join(os.path.dirname(__file__), 'intro.html')
        self.response.out.write(template.render(path, template_values))

class MainPage(webapp.RequestHandler):
    @login_required
    def get(self):

        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = 'Logout'
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = 'Login'

        scheme, host, path, param, query, frag = urlparse.urlparse(self.request.url)
        args = cgi.parse_qs(query)
        

        #Now get the user!!!
        person = getCurrentPerson()

        self.thetrans = self.parseArg(args, "trans")
        self.thebook = self.parseArg(args, "book")
        self.thechapno = self.parseArg(args, "chap")

        #debug = "The bok:" + self.thebook + "."
        debug = "ok!"

        # Get consistenct between the saved, and the ones we will actually display
        if (self.thebook == None):
           #Lets get just a specific translation of a chapter.
           self.thetrans = person.lasttrans
           self.thebook = person.lastread
           self.thechapno = person.automarks[self.thebook - 1]
        else:
           person.lasttrans = self.thetrans
           #TODO: Now need to decode the book if passed in, so as to get the actual book value
           self.thebook = int(int(self.thebook) / 1000)
           person.lastread = int(self.thebook)
           person.automarks[person.lastread - 1] = int(self.thechapno)
           person.put()

        self.thebook = int(self.thebook)
        self.thechapno = int(self.thechapno)

        #Grrr. Need to map BBE to BEB
        trans = self.thetrans
        if (trans == 'BBE'):
          trans = "BEB"
        #trans = "WEB"
        chapters_query = Chapter.all().filter("translation =", trans).filter("bookno =", self.thebook).filter("chapno =", self.thechapno)
        chapters = chapters_query.fetch(1)

        #TODO: it would be better (but slower) for this to be obtained from the database - e.g. look for Gen,1 and then see what translations turn up...
        self.translist = ["BBE", "WEB", "KJV"]

        #The booklist is the booknames (with values as their id's)
        #TODO: Actually might be better for the values to also encode the "recent chap" data, as then that becomes available to
        # the .js when a book is selected, so that the redone chaplist, can have that chap selected.
        #self.booklist = Book.all().filter("translation =", self.thetrans).order('bookno').fetch(66)  
        self.booklist = Book.all().filter("translation =", trans).order('bookno').fetch(66)  

        #Encode the booklist, to include the person automark data
        self.autolist = []
        for i in range(66):
            nextbook = Book()
            nextbook.bookname = self.booklist[i].bookname
            #So the encoded bookno is the normal one, times 1000, + persons auto value
            nextbook.bookno = ((i+1) * 1000) + person.automarks[i]
            nextbook.defaultchap = person.automarks[i]
            self.autolist.append(nextbook)

        #Also encode the bookno
        self.autobook = (self.thebook * 1000) + person.automarks[self.thebook - 1]
     
        self.thebookname = self.booklist[self.thebook - 1].bookname

        #The chaplist is just the range 1.. last chapter
        #self.chaplist = range(1, self.booklist[self.thebook - 1].chapcount + 1)
        self.chaplist = []
        for i in range(1, self.booklist[self.thebook - 1].chapcount + 1):
            self.chaplist.append(i)

        #Now get the notes for this user.
        #TODO: This will need to be prettied up in the future...dates etc.
        thenotes = Note.all().filter("author =", person.user).filter("bookno =", int(self.thebook))
        thenotes = thenotes.filter("chapno =", int(self.thechapno)).order("extent").fetch(20)
        #debug = "chapno=" + str((self.thechapno)) + "bookno=" + str((self.thebook)) + ", notes#= ", str(len(thenotes))

        #transtext = data.translation_text[self.thetrans]
        transtext = data.translation_text[trans]

        template_values = {
            'url': url,
            'url_linktext': url_linktext,
            'chapters':     chapters,
            'thetrans':     self.thetrans,
            'thebook':      self.autobook,
            'thebookname':  self.thebookname,
            'thechapno':    self.thechapno,
            'translist':    self.translist,
            'booklist':     self.autolist,
            'chaplist':     self.chaplist,
            'transtext':    transtext,
            'debug':        debug,
            'notes':        thenotes,
            }

        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))

    def parseArg(self, args, argname):
      try:
        ret = args[argname][0]
      except:
        ret = None
      return ret

class AddNote(webapp.RequestHandler):
    def post(self):
        newnote = Note()
        person = getCurrentPerson()
        newnote.author = person.user
        #Increment first, so that notes are numbered from 1, and opusno hodl the number of notes by that author
        person.opusno += 1
        newnote.opusno = person.opusno
        newnote.bookno = person.lastread
        newnote.chapno = person.automarks[newnote.bookno - 1]
        try:
            newnote.start = int(self.request.get('vstart'))
        except:
            newnote.start = 1
        try:
            newnote.finish = int(self.request.get('vfinish'))
        except:
            chapters_query = Chapter.all().filter("translation =", "WEB").filter("bookno =", newnote.bookno).filter("chapno =", newnote.chapno)
            chapters = chapters_query.fetch(1)            
            newnote.finish = chapters[0].versescount
        newnote.extent = (1000 * newnote.start) - newnote.finish
        try:
            newnote.shared = int(self.request.get('sharing'))
        except:
            newnote.shared = 0
        newnote.content = self.request.get('content')
        newnote.put()
        person.put()
        self.redirect('/main')

class DelNote(webapp.RequestHandler):
    def post(self):
        self.redirect('/main')  


class Privacy(webapp.RequestHandler):
    def get(self):

        template_values = {
            }

        path = os.path.join(os.path.dirname(__file__), 'privacy.html')
        self.response.out.write(template.render(path, template_values))


class UserAgreement(webapp.RequestHandler):
    def get(self):
   
        template_values = {
            }

        path = os.path.join(os.path.dirname(__file__), 'useragreement.html')
        self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [('/', Intro),
                                      ('/main', MainPage),
                                      ('/addnote', AddNote),
                                      ('/delnote', DelNote),
                                      ('/privacy', Privacy),
                                      ('/useragreement', UserAgreement)
],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
